package com.springboot.demo.threadpool;

import java.util.concurrent.SynchronousQueue;

public class SynchronousQueueExample {
    public static void main(String[] args) {
        SynchronousQueue<String> synchronousQueue = new SynchronousQueue<>();

        // 创建一个生产者线程
        Thread producer = new Thread(() -> {
            try {
                String data = "Hello";
                System.out.println("生产者线程插入数据: " + data);
                synchronousQueue.put(data); // 插入元素，会被阻塞，直到有消费者线程来获取
                System.out.println("生产者线程完成");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        // 创建一个消费者线程
        Thread consumer = new Thread(() -> {
            try {
                Thread.sleep(2000); // 休眠2秒模拟一些其他操作
                String data = synchronousQueue.take(); // 获取元素，会触发生产者线程插入操作
                System.out.println("消费者线程获取数据: " + data);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        producer.start();
        consumer.start();
    }
}
